#include "Events.h"
#include "RandomSystem.h"

#include <cassert>
#include <fstream>
#include <iostream>

EventGenerator::EventGenerator(const std::string& i_filename)
{
	ParseEventMessages(i_filename);
}

void EventGenerator::ParseEventMessages(const std::string& i_filename)
{
	std::ifstream fileStream;
	fileStream.open(i_filename.c_str(), std::ifstream::in);

	if (fileStream.fail())
	{
		std::cout << "ERROR" << std::endl;
		assert(0);
	}

	char buffer[64];
	std::string line;

	fileStream.getline(buffer, 64);
	line = buffer;

	while (fileStream.good() && line != "#eof")
	{		
		assert(buffer[0] == '#');
		std::string category = line.substr(1, line.length()-1);

		std::vector<std::string> temp;
		fileStream.getline(buffer, 64);
		line = buffer;

		while(line.at(0) != '#')
		{
			temp.push_back(line);
			fileStream.getline(buffer, 64);
			line = buffer;
		}

		m_eventMessages.insert(std::make_pair<std::string, std::vector<std::string>>(category, temp));
	}
}

std::string EventGenerator::RandomEventMessageInCategory(const std::string& i_category, const std::string& i_name) const
{
	static char s_arrayMessage[256];
	EventMap::const_iterator cit = m_eventMessages.find(i_category);
	assert(cit != m_eventMessages.end() && "categoria di evento inesistente");

	const std::vector<std::string>& messages = cit->second;

	int random = RandIntBetween(0, messages.size() - 1);
	const std::string& message = messages[random];
	size_t length = message.length() + i_name.length() + 1;
	sprintf_s(s_arrayMessage, length, message.c_str(), i_name.c_str());
	
	return s_arrayMessage;
}
